<template>
  <!-- 登录弹框 -->
  <view>
    <uni-popup :maskClick="false" ref="tipsPopup" type="bottom">
      <view class="casing bg-white w-full">
        <view class="title">{{
          invitationCode ? "请确认邀请人信息" : "请完善用户信息"
        }}</view>
        <view class="txt"
          >邀请人信息是推广人获得权益的必要条件，请仔细核对！</view
        >
        <view
          class="content bg-white flex align-center justify-between"
          v-if="invitationCode"
        >
          <view class="leftPart">邀请码</view>
          <view class="middlePart">
            <input
              type="text"
              v-model="inviteCode"
              class="middleInput h-full"
            />
          </view>
          <view class="rightPart">选填</view>
        </view>
        <form
          @submit="formSubmit"
          class="profilePicture flex flex-column align-center justify-center"
          v-else
          report-submit="true"
        >
          <view class="flex justify-center">
            <button
              class="imgList"
              open-type="chooseAvatar"
              @chooseavatar="onChooseAvatar"
            >
              <image
                :src="
                  avatarUrl
                    ? avatarUrl.includes('crmebimage')
                      ? 'https://app-cangshu.oss-rg-china-mainland.aliyuncs.com/asssets/img/notLogged.png'
                      : avatarUrl
                    : avatarUrl
                "
                class="avatar"
                mode="scaleToFill"
              />
              <image
                class="userInfoPhoto"
                src="https://app-cangshu.oss-rg-china-mainland.aliyuncs.com/asssets/img/userInfoPhoto.png"
                mode="scaleToFill"
              />
            </button>
          </view>
          <view class="tips">点击上传头像</view>
          <view>
            <input
              type="nickname"
              name="nickname"
              :value="nickname"
              class="imply"
              placeholder="点击完善用户昵称"
              maxlength="10"
            />
            <text class="tips revtion-50">{{
              "（默认为随机昵称、可修改）"
            }}</text>
          </view>
          <button
            class="logOnBtn"
            formType="submit"
            :class="invitationCode ? 'col-white' : 'col-balck w-690'"
          >
            保存信息
          </button>
        </form>
        <!-- <view class="imply">点击完善用户昵称</view> -->
        <button
          class="logOnBtn"
          v-if="invitationCode"
          @click="getBindingRelationShip"
          :class="invitationCode ? 'col-white' : 'col-balck'"
        >
          确认
        </button>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import {
  entryInvitationCode,
  bindingRelationShip,
  userEdit,
} from "@/api/user.js";
import { mapGetters } from "vuex";
import { HTTP_REQUEST_URL } from "@/config/app";
import { Debounce } from "@/utils/validate.js";
// import { bindingRelationShip } from "@/api/user.js";
export default {
  name: "",
  computed: mapGetters(["isLogin"]),
  props: {
    icode: {
      type: String,
      default: "",
    },
    isHave: {
      type: Boolean,
      default: false,
    },
    userInfoData: {
      type: Object,
      default: {},
    },
    operationLogin: {
      type: Boolean,
      default: false,
    },
    mark: {
      type: Boolean,
      default: false,
    },
    optionsData: {
      // 首页参数数据
      type: Object,
      default: {},
    },
    register: {
      // 注册用户就有字段为register
      type: String,
      default: "",
    },
  },
  data() {
    return {
      infoData: {}, // 用户信息
      invitationCode: true,
      prefix: "https://prodapi.huikexin.fun",
      avatarUrl: "",
      nickname: "",
      inviteCode: null, // 邀请码
    };
  },
  watch: {
    icode: {
      handler(val) {
        this.inviteCode = JSON.parse(JSON.stringify(val));
      },
      immediate: true,
    },
    isHave: {
      handler(val) {
        this.invitationCode = !val;
      },
      immediate: true,
    },
    userInfoData: {
      handler(val) {
        this.infoData = JSON.parse(JSON.stringify(val));
        this.nickname = val.nickname == "&mark" ? "" : val.nickname;
        this.avatarUrl = val.avatar;
      },
      immediate: true,
    },
  },
  mounted() {},
  methods: {
    /**
     * 提交修改
     */
    formSubmit: Debounce(function (e) {
      let that = this;
      let value = e.detail.value;
      if (!value.nickname)
        return that.$util.Tips({
          title: "用户姓名不能为空",
        });
      userEdit({
        avatar: that.avatarUrl,
        birthday: that.infoData.date ? that.infoData.date : "2000-01-01",
        city: that.infoData.city ? that.infoData.city : "广州市",
        province: that.infoData.province ? that.infoData.province : "广东省",
        nickname: value.nickname,
        sex: that.infoData.sex ? that.infoData.sex : 0,
      })
        .then((res) => {
          uni.hideLoading();
          that.$util.Tips({
            title: "保存成功",
            icon: "success",
          });
          setTimeout(function () {
            that.cancel();
            if (Object.keys(that.optionsData).length) {
              // 前往成为商户
              if (that.optionsData.userId) {
                uni.navigateTo({
                  url: `/pages/merchantInfo/inviteBecomeMerchants?userId=${that.optionsData.userId}`,
                });
                // 前往成为推荐官
              } else if (that.optionsData.barCodeStr) {
                uni.navigateTo({
                  url: `/pages/supplier/complete?barCodeStr=${that.optionsData.barCodeStr}`,
                });
              }
              // else if (that.optionsData.tenantId) {
              //   // 对接商户付款
              //   uni.navigateTo({
              //     url: `/pages/emption/index?tenantId=${that.optionsData.tenantId}&register=${that.register}`,
              //   });
              // }
            }
            if (this.mark) {
              this.$emit("getUserInfo");
            }
          }, 1000);
        })
        .catch((msg) => {
          uni.hideLoading();
          return that.$util.Tips({
            title: msg || "保存失败，您并没有修改",
          });
        });
    }),
    // 是否绑定关系
    getBindingRelationShip() {
      if (this.inviteCode) {
        bindingRelationShip().then((res) => {
          if (!res.data) {
            this.sureBtn();
          } else {
            this.$util.Tips({
              title: "该用户已有上级",
            });
          }
        });
      } else {
        this.invitationCode = false;
      }
    },
    /**
     * 小程序端上传头像
     *
     */
    onChooseAvatar(e) {
      uni.showLoading({
        title: "加载中...",
      });
      let that = this;
      const { avatarUrl } = e.detail;
      that.$util.uploadImgs(
        avatarUrl,
        {
          url: "upload/image",
          name: "multipart",
          model: "maintain",
          pid: 0,
        },
        (res) => {
          that.avatarUrl = that.prefix + "/" + res.data.url;
          uni.hideLoading();
        },
        (err) => {
          uni.hideLoading();
        }
      );
    },
    // 确定邀请码
    sureBtn() {
      if (this.inviteCode == this.$store.state.app.userInfo.icode) {
        this.$util.Tips({
          title: "不能绑自己的邀请码",
        });
      } else {
        let str = "";
        if (this.inviteCode.indexOf("TY") != -1) {
          str = this.inviteCode.slice(0, -2);
        } else {
          str = this.inviteCode;
        }
        entryInvitationCode(str)
          .then((res) => {
            this.$util.Tips({
              title: "操作成功",
            });
            if (this.operationLogin) this.invitationCode = false;
            else this.cancel();
            if (this.mark) {
              this.$emit("logOn");
            }
          })
          .catch((err) => {
            this.$util.Tips({
              title: err,
            });
          });
      }
    },
    // 打开登录弹框
    open() {
      this.$refs.tipsPopup.open();
    },
    // 取消登录弹框
    cancel() {
      this.$refs.tipsPopup.close();
    },
  },
};
</script>

<style lang="scss" scoped>
.casing {
  padding: 47rpx 31rpx 59rpx 31rpx;
  background: linear-gradient(180deg, #e7ecf5 0%, #ffffff 100%);
  border-radius: 40rpx 40rpx 0rpx 0rpx;
  .title {
    padding: 0rpx 9rpx;
    font-family: PingFang SC, PingFang SC;
    font-size: 35rpx;
    color: #000000;
  }
  .txt {
    margin-top: 29rpx;
    padding: 0rpx 9rpx;
    font-weight: 300;
    font-size: 26rpx;
    color: #939393;
  }
  .logOnBtn {
    margin-top: 50rpx;
    line-height: 77rpx;
    height: 77rpx;
    text-align: center;
    background: #11cc7b;
    border-radius: 38rpx;
    font-size: 28rpx;
    // color: #ffffff;
  }
}
.content {
  border-radius: 14rpx;
  margin-top: 54rpx;
  padding: 0rpx 48rpx;
  height: 143rpx;
  .leftPart {
    font-size: 35rpx;
    color: #000000;
  }
  .rightPart {
    font-size: 31rpx;
    color: #939393;
  }
  .middlePart {
    height: 50rpx;
    .middleInput {
      font-size: 31rpx;
      color: #000000;
    }
  }
}
.profilePicture {
  margin-top: 35rpx;
  .imgList {
    position: relative;
    width: 137rpx;
    background: transparent;
    .userInfoPhoto {
      width: 38rpx;
      height: 38rpx;
      position: absolute;
      bottom: 0rpx;
      right: 4rpx;
    }
  }
  .avatar {
    height: 137rpx;
    width: 137rpx;
    border-radius: 50%;
  }
  .tips {
    text-align: center;
    margin-top: 14rpx;
    font-weight: 300;
    font-size: 24rpx;
    color: #535353;
  }
  .imply {
    text-align: center;
    margin-top: 65rpx;
    font-size: 30rpx;
    color: #000000;
  }
}
.w-690 {
  width: 690rpx !important;
}
.revtion-50 {
  position: relative;
  left: 28%;
}
</style>
